
// 计算平均值功能
function avg(arr){
    var sum = 0;
    for(var j=0;j<arr.length;j++){
        sum += arr[j];
    }
    return (sum/arr.length)
}

// 范围随机数
function random(max, min){
    return Math.round(Math.random() * (max-min) + min);
}

// 获取日期对象的每一部分，为了方便日期的格式化
function getDate(){
    var d = new Date();
    var y = d.getFullYear();
    var m = d.getMonth() + 1;
    var mydate = d.getDate();

    var myday = d.getDay();
    switch(myday){
        case 0:myday = "星期日";break;
        case 1:myday = "星期一";break;
        case 2:myday = "星期二";break;
        case 3:myday = "星期三";break;
        case 4:myday = "星期四";break;
        case 5:myday = "星期五";break;
        case 6:myday = "星期六";break;
    }

    var h = d.getHours();
    var muts = d.getMinutes();
    var s = d.getSeconds();

    var mls = d.getMilliseconds();

    return {
        year:y,
        month:cz(m),
        date:cz(mydate),
        day:myday,
        hours:cz(h),
        minutes:cz(muts),
        seconds:cz(s)
    }
}

// 数值补零
function cz(n){
    return n<10 ? "0"+n : n;
}

// 计算两个日期之间的差值
function dateDiff(date1,date2){
    var d1 = new Date(date1);
    // 默认参数（可选参数）的处理逻辑
    var d2 = date2 ? new Date(date2) : new Date();

    var time = Math.abs(d2.getTime() - d1.getTime());

    var day = parseInt(time/1000/60/60/24);
    var hours = parseInt((time - day*24*60*60*1000)/1000/60/60);
    var mut = parseInt((time - day*24*60*60*1000 - hours*60*60*1000)/1000/60);
    var sec = (time - day*24*60*60*1000 - hours*60*60*1000 - mut*60*1000)/1000;

    return {
        day,
        hours,
        mut,
        sec
    }
}

// 获取样式的兼容封装
function getStyle(ele, cssAttr){
    if(ele.currentStyle){
        return ele.currentStyle[cssAttr];
    }else{
        return getComputedStyle(ele, false)[cssAttr];
    }
}


// 处理事件冒泡的兼容封装
function stopBubble(e){
    if(e.stopPropagation){
        e.stopPropagation();
    }else{
        e.cancelBubble = true;
    }
}

// 监听式删除事件的兼容封装
function removeEvent(ele, type, cb){
    if(ele.detachEvent){
        ele.detachEvent("on"+type, cb);
    }else{
        ele.removeEventListener(type, cb);
    }
}

// 监听式绑定事件的兼容封装
function addEvent(ele, type, cb){
    if(ele.attachEvent){
        ele.attachEvent("on"+type, cb);
    }else{
        ele.addEventListener(type, cb);
    }
}

// 阻止默认事件的封装
function stopDefault(e){
    if(e.preventDefault){
        e.preventDefault();
    }else{
        e.returnValue = false;
    }
}